package Offer.offer2017;


import domain.ListNode;

/**
 * 合并两个排序的列表
 * Created by 雷文康 on 2017/12/31.
 */
public class Test17 {
    public static void main(String[] args) {
        ListNode p1 = new ListNode(2);
        ListNode p2 = new ListNode(3);
        ListNode p3 = new ListNode(5);
        ListNode p4 = new ListNode(7);
        p1.next=p2;
        p2.next=p3;
        p3.next=p4;
        p4.next=null;
        ListNode p5 = new ListNode(2);
        ListNode p6 = new ListNode(3);
        ListNode p7 = new ListNode(6);
        ListNode p8 = new ListNode(8);
        p5.next=p6;
        p6.next=p7;
        p7.next=p8;
        p8.next=null;
//		ListNode p = merge(p1,p5);
        ListNode p = mergeList(p1,p5);
        while(p!=null)
        {
            System.out.print(p.val);
            p=p.next;
        }
    }

    public static ListNode mergeList(ListNode list1 , ListNode list2){
        if (list1 == null) {
            return list2;
        }

        if (list2 == null) {
            return list1;
        }
        ListNode newHead = null;
        if (list1.val <= list2.val) {
            newHead = list1;
            newHead.next = mergeList(list1.next, list2);
        } else {
            newHead = list2;
            newHead.next = mergeList(list1, list2.next);
        }
        return newHead;
    }
}
